<template>
  <div id="detail" class="container">
    <el-card class="box-card" v-show="show">
      <div slot="header" class="clearfix">
        <span>{{ task.title }} </span>
      </div>
      <div>
        悬赏金额： <span style="color:#ff4c4c;"> {{ task.reward }} </span> Nas
      </div>
      <div>
        悬赏状态：{{ task.status }}
      </div>
      <div>
        创建日期：{{ formatTime(task.timestamp) }}
      </div>
      <div>
        创建人：<a v-bind:href="explorer + 'address/' + task.from" target="_blank">{{ task.from }}</a>
      </div>
      <div v-show="task.finished != '0'">
        领取人：<a v-bind:href="explorer + 'address/' + task.to" target="_blank">{{ task.to }}</a>
      </div>
      <div>
        {{ task.content }}
      </div>
      <div v-show="take" class="take">
        <el-input v-model="taskCode" placeholder="请输入领奖码">
          <el-button slot="append" @click="onTake" v-loading.fullscreen.lock="fullscreenLoading">领取悬赏</el-button>
        </el-input>
      </div>
    </el-card>

    <div class="result" v-show="success">
      <div>
        <span style="color: red;">请等待钱包确认交易成功</span>，将交易写入区块链。
      </div>
      <div>
        您的交易Hash（点击查看交易状态）:
      </div>
      <div>
        <a v-bind:href="explorer + 'tx/' + txhash" target="_blank">{{ txhash }}</a>
      </div>
    </div>
  </div>
</template>
<script>

  import util from '../util'

  export default {
    data () {
      return {
        fullscreenLoading: false,
        show: false,
        take: true,
        success: false,
        txhash: '',
        taskId: '',
        taskCode: '',
        explorer: util.config.explorer,
        task: {
          title: '',
          reward: '',
          content: '',
          status: '',
          txhash: '',
          from: '',
          timestamp: '',
          to: '',
          finished: 0
        }
      }
    },
    created() {
      console.log(this.$route.params.id);
      if (this.$route.params.id) {
        this.taskId = this.$route.params.id;
        this.onQuery();
      }
      else {
        this.taskId = '';
        this.success = false;
      }
    },
    methods : {
      openFullScreen() {
        this.fullscreenLoading = true;
        setTimeout(() => {
          this.fullscreenLoading = false;
        }, 2000);
      },
      formatReward(r) {
        return util.nebulas.Unit.fromBasic(r, 'nas').toString();
      },
      formatTime(t) {
        var date = new Date(t*1000);
        var hours = "0" + date.getHours();
        var minutes = "0" + date.getMinutes();
        var seconds = "0" + date.getSeconds();
        var year = date.getFullYear();
        var month = "0" + date.getMonth();
        var day = "0" + date.getDate();
        var formattedTime =  year + '-' + month.substr(-2) + '-' + day.substr(-2) + ' ' + hours.substr(-2) + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
        return formattedTime;
      },
      onQuery() {
        if(this.taskId.length < 1) {
          this.fullscreenLoading = false;
          this.$message({
            showClose: true,
            message: '请输入有效的悬赏ID！',
            type: 'error'
          });
        }
        else {
          this.fullscreenLoading = true;
          setTimeout(() => {
            this.fullscreenLoading = false;
          }, 5000);

          var args = '["' + this.limit + '", "' + this.offset + '", "1"]';
          console.log(args);
          util.nebPay.simulateCall(
            util.config.dappaddr,
            '0',
            'taskinfo',
            '["' + this.taskId + '"]',
            {
              listener: (data) => {
                this.fullscreenLoading = false;
                if (data.execute_err && data.execute_err == 'contract check failed') {
                  this.$alert('请确认钱包插件网络为「Mainnet」，切换后刷新重试', '网络错误', {
                    confirmButtonText: '确定'});
                } else {
                  var result = JSON.parse(data.result);
                  this.task.title = result.title;
                  this.task.reward = util.nebulas.Unit.fromBasic(result.reward, "nas").toString();
                  this.task.content = result.content;
                  this.task.finished = result.finished;
                  this.task.txhash = result.txhash;
                  this.task.from = result.from;
                  this.task.timestamp = result.timestamp;
                  this.task.to = result.to;
                  if (this.task.finished == 0) {
                    this.task.status = '进行中';
                    this.take = true;
                  }
                  else {
                    this.task.status = '已完成';
                    this.take = false;
                  }
                  this.show = true;
                }
              }
            });
        }
      },
      listenWallet() {
        window.addEventListener('message', function(resp) {
          console.log("nebpay: received resp.data: " + JSON.stringify(resp.data));
          if(resp.data.src !== "content")
            return;
          if(typeof resp.data.resp !== 'object')
            return;
          var key = resp.data.serialNumber;
          console.log(resp.data.resp);
          var txhash = resp.data.resp.txhash;
          console.log('->key: ' + key);
          console.log('->txthash: ' + txhash);
          this.txhash = txhash;
          this.success = true;
        }.bind(this));
      },
      onTake() {
        if (this.taskCode.length < 1) {
          this.$message({
            showClose: true,
            message: '请输入有效的领奖码！',
            type: 'error'
          });
        }
        else {
          var to = util.config.dappaddr;
          var value = 0;
          var callFunc = "take";
          var callArgs = '["' + this.task.txhash + '", "' + this.taskCode + '"]';
          console.log("args: " + callArgs);

          this.listenWallet();
          serialNumber = util.nebPay.call(to, value, callFunc, callArgs, {
            listener: (data) => {
              if (typeof data === 'object') {
                console.log("listener:" + data);
              } else {
                this.$message({
                  showClose: true,
                  message: '交易被取消，悬赏创建失败！',
                  type: 'error'
                });
              }
            }
          });

          console.log('serialnumber: ' + serialNumber);
        }
      }
    }
  };

</script>

<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 98%;
    margin: auto;
    margin-top: 20px;
  }

  .container {
    background-color: #fff;
    padding: 30px 15px 30px 15px;
    min-height: 400px;
  }
  .take {
    padding-top: 20px;
  }
  .result {
    margin-top: 20px;
    padding: 20px;
  }
</style>
